/**
 * @file shared_mutex.cpp
 * @author your name (you@domain.com)
 * @brief shared_mutex使用demo
 * @version 0.1
 * @date 2022-04-15
 * 
 * @copyright Copyright (c) 2022
 * 
 */

#include <thread>
#include <shared_mutex>
#include <iostream>
#include <algorithm>

/**
 * shared_lock<shared_mutex>类似于linux中的ReadLock，可共享
 * unique_lock<shared_mutex>类似于linux中的WriteLock，不可共享
 * 
 */

std::shared_mutex sh_mtx;

void funRead(void)
{
    std::shared_lock<std::shared_mutex> lk(sh_mtx);
    std::cout<< "fun Read enter...." << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout<< "fun Read exit...." << std::endl;
}

void funWrite(void)
{
    std::unique_lock<std::shared_mutex> lk(sh_mtx);
    std::cout<< "fun Write enter ...." << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout<< "fun Write exit ...." << std::endl;
}

int main(void)
{
    constexpr int threadCnt = 5;
    std::thread tRead[threadCnt];
    std::thread tWrite[threadCnt];

    generate(begin(tRead), end(tRead), [](){
        return std::thread(funRead);
    });

    generate(begin(tWrite), end(tWrite), [](){
        return std::thread(funWrite);
    });

    for_each(begin(tRead), end(tRead), [](std::thread& t){
        t.join();
    });

    for_each(begin(tWrite), end(tWrite), [](std::thread& t){
        t.join();
    });
}